<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/13
 * Time: 9:16
 */

header('Content-type:text/html; charset=utf-8');
// 开启Session
session_start();

//接收用户的登录信息
$username = trim($_POST['username']);
$password = trim($_POST['password']);

// 处理用户登录信息
if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    // 判断提交的登录信息
    if (($username == '') || ($password == '')) {
        // 若为空,视为未填写,提示错误,并3秒后返回登录界面
        header('refresh:3; url=login.html');
        echo "用户名或密码不能为空,系统将在3秒后跳转到登录界面,请重新填写登录信息!";
        exit;
    } else {
        # 用户名或密码错误,同空的处理方式
        sqlCheck($username, $password);
    };
};

//从数据库读取用户信息
function sqlCheck($username, $password) {
 //数据库连接
 $mysqli = new mysqli("localhost", "root", "gcy888999", "blog");
    $mysqli->query("SET NAMES utf8");
 


 //检测连接
 if(mysqli_connect_error()) {
     die("连接失败: " . $mysqli->connect_error);
 }

 $sql = "SELECT username, password FROM user where username ='".$username. "' AND password='" .$password . "'";
 $result = $mysqli->query($sql);
 if($result->num_rows > 0) {
     while ($row = mysqli_fetch_assoc($result)) {
         loginMethod($row["username"], $row["password"] );
     }
 }else {
    header('refresh:3; url=login.html');
    echo "用户名或密码错误,系统将在3秒后跳转到登录界面,请重新填写登录信息!";
    exit;
 }

}

//登陆账号信息校验
function loginMethod($username1, $password1) {
    if (($username = $username1) && ($password = $password1)) {
        $_SESSION['username'] = $username;
        $_SESSION['islogin'] = 1;
        // 若勾选7天内自动登录,则将其保存到Cookie并设置保留7天
        if ($_POST['remember'] == "yes") {
            setcookie('username', $username, time() + 7 * 24 * 60 * 60);
            setcookie('code', md5($username . md5($password)), time() + 7 * 24 * 60 * 60);
        } else {
            // 没有勾选则删除Cookie
            setcookie('username', '', time() - 999);
            setcookie('code', '', time() - 999);
        }
        // 处理完附加项后跳转到登录成功的首页
        header('location:index.php');
    };
};